package com.vt.auth.endpoint;

import cn.hutool.core.util.StrUtil;
import com.vt.admin.api.feign.RemoteUserService;
import com.vt.common.core.constant.SecurityConstants;
import com.vt.common.core.util.R;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @Auther: PanZha
 * @Date: 2018/10/12 17:55
 * 删除token端点
 */
@RestController
@AllArgsConstructor
@RequestMapping("/oauth")
public class OauthTokenEndpoint {
    private static final String APP_OAUTH_ACCESS = SecurityConstants.APP_PREFIX + SecurityConstants.OAUTH_PREFIX + "access:";
    private final TokenStore tokenStore;
    private final RedisTemplate redisTemplate;

    private final RemoteUserService remoteUserService;

    /**
     * 退出token
     *
     * @param authHeader Authorization
     */
    @GetMapping("/removeToken")
    public R<Boolean> logout(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        if (StringUtils.hasText(authHeader)) {
            String tokenValue = authHeader.replace("Bearer", "").trim();
            OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
            if (accessToken == null || StrUtil.isBlank(accessToken.getValue())) {
                return new R<>(false, "退出失败，token 为空");
            }
            tokenStore.removeAccessToken(accessToken);
        }

        return new R(Boolean.TRUE);
    }

    /**
     * 令牌管理调用
     *
     * @param token token
     * @param from  内部调用标志
     * @return
     */
    @DeleteMapping("/delToken/{token}")
    public R<Boolean> delToken(@PathVariable("token") String token, @RequestHeader(required = false) String from) {
        if (StrUtil.isBlank(from)) {
            return null;
        }
        return new R(redisTemplate.delete(APP_OAUTH_ACCESS + token));
    }
}
